const fs= require('fs');
const tools=require('./tools.js');
let {HomePath,getFileType}=tools;
const auConfig=global.au.config;
const uuid=require('node-uuid');
let startService=require(tools.HomePath('/core/.au/service.js'));

function createdTempFile(path,fileContent,filtType='.js'){
    path=path+'/'+uuid.v4()+filtType;
    fs.writeFileSync(path,fileContent);
    global['au'].tempFilePath.push(path);
    return path;
}

function webpackInitEntry(obj={}){
    //初始化对象
    let tempDir=HomePath('/core/.au/.build');
    //创建目录
    if(fs.existsSync(tempDir)){
        tools.deleteFile(tempDir);
    }
    fs.mkdirSync(tempDir);
    //创建文件
    obj['extension/core/background']=createdTempFile(tempDir,tools.initScript(auConfig.serviceHost+'/background.js'));
    obj['extension/core/content']=createdTempFile(tempDir,tools.initScript(auConfig.serviceHost+'/content.js'));
    obj['extension/core/popup']=createdTempFile(tempDir,tools.initScript(auConfig.serviceHost+'/popup.js'));
    //编译.vue文件
    function reload(path){
        function getFilePath(filePath){
            let bakFilePath=filePath;
            if(!fs.existsSync(filePath)){
                //文件不存在 js
                filePath=bakFilePath+'.js';
                if(!fs.existsSync(filePath)){
                    filePath=bakFilePath+'/index.js';
                    if(!fs.existsSync(filePath)){
                        return '';
                    }
                }
            }
            return filePath;
        }
        let filePath=getFilePath(HomePath('/src/modules/'+path));
        if(filePath){
            //加入模块
            let key='service/modules/'+path;
            global.au.modulesPath[key]=filePath;
            obj[key]=filePath;
        }
    }
    if(auConfig.modules){
        auConfig.modules.forEach((it)=>{
            if (typeof it.module ==="string") {
                reload(it.module);
            }
        });
    }
    if(global.isDev){
        //启动服务
        //startService();
    }
    return obj;
}


module.exports={
    entry:webpackInitEntry,

};
